find all factors of a given number

91

find all factors of a given number -

public List<int> Factor(int number) 
{
    var factors = new List<int>();
    int max = (int)Math.Sqrt(number);  // Round down

    for (int factor = 1; factor <= max; ++factor) // Test from 1 to the square root, or the int below it, inclusive.
    {  
        if (number % factor == 0) 
        {
            factors.Add(factor);
            if (factor != number/factor) // Don't add the square root twice!  Thanks Jon
                factors.Add(number/factor);
        }
    }
    return factors;
}

Find Factors of a Number Using Function -

def FindFact(n):
    for i in range(1, n+1):
        if n % i == 0:
            print(i, end=" ")
    print()

print("Enter a Number: ", end="")
try:
    num = int(input())
    print("\nFactors of " +str(num)+ " are: ", end="")
    FindFact(num)
except ValueError:
    print("\nInvalid Input!")

Comments

Submit
0 Comments